<template>
  <div class="container view-container">
    <div class="top">
      <iframe id="divPlugin" class="plugin"></iframe>
    </div>
    <div class="loginInfo">
      <el-form class="form">
        <el-form-item class="item" label="ip地址">
          <el-input v-model="data.ip" placeholder="ip地址"></el-input>
        </el-form-item>
        <el-form-item class="item" label="端口号">
          <el-input v-model="data.port" placeholder="端口号"></el-input>
        </el-form-item>
        <el-form-item class="item" label="用户名">
          <el-input v-model="data.userName" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item class="item" label="密码">
          <el-input v-model="data.password" placeholder="密码" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div class="login">
        <el-button class="item" type="primary" @click="mark">标注</el-button>
        <el-button class="item" type="primary" @click="loginClick(data)">登录</el-button>
        <el-button class="item" type="primary" @click="loginoutClick(data)">退出</el-button>
        <el-button class="item2" type="primary" @click="clickGetDeviceInfo(data)">获取基本信息</el-button>
        <div class="login-list">
          <div class="title">通道列表:</div>
          <el-select v-model="channelValue" @change="startRealPlay(data)" placeholder="" size="large">
            <el-option v-for="item in channleList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="left">
        <div class="title">预览</div>
        <div class="btn-preview">
          <el-button type="primary" @click="startRealPlay(data)">开始预览</el-button>
          <el-button type="primary" @click="clickStopRealPlay">停止预览</el-button>
          <el-button type="primary" @click="clickOpenSound">打开声音</el-button>
          <el-button type="primary" @click="clickCloseSound">关闭声音</el-button>
        </div>
        <div class="title">云台控制</div>
        <div class="btn-ctrl">
          <el-button
            v-for="(item, index) in leftCtrBtnList"
            :key="index"
            class="btn"
            type="primary"
            @mousedown="mouseDownPTZControl(item.value)"
            @mouseup="mouseUpPTZControl()"
            >{{ item.name }}</el-button
          >
        </div>
      </div>
      <div class="right">
        <div class="title">
          <div class="right-title">窗口分割数量</div>
          <div class="select">
            <el-select v-model="windowValue" @change="changeWndNum(windowValue)" placeholder="1*1" size="large">
              <el-option v-for="item in windowOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </div>
        </div>
        <div class="btn-ctrl">
          <el-button
            v-for="(item, index) in rightCtrlBtnList"
            :key="index"
            class="btn"
            type="primary"
            @mousedown="rightCtrlDown(item.value)"
            @mouseup="rightCtrlUp(item.value)"
            >{{ item.name }}</el-button
          >
        </div>
      </div>
    </div>

    <el-dialog v-model="dialogVisible" :before-close="handleClose" append-to-body>
      <div class="dialogContent">
        <div class="title">
          <div class="item">通道：{{ markInfo.channelNo }}</div>
          <div class="item">时间：{{ markInfo.createTime }}</div>
        </div>
        <el-form
          class="form"
          ref="formRef"
          :model="markInfo"
          :rules="markInfo.rules"
          hide-required-asterisk
          label-position="top"
        >
          <el-form-item class="type" prop="type">
            <el-input v-model="markInfo.type" maxlength="10" placeholder="请输入标注分类标签"></el-input>
          </el-form-item>
          <el-form-item class="desc" prop="desc">
            <el-input
              v-model="markInfo.desc"
              type="textarea"
              input-style="min-height: 31px; height: 210px; margin-top:-20px"
              placeholder="请输入文本标注"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="submit(false)">取消</el-button>
          <el-button type="primary" @click="submit(true)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onActivated, onDeactivated, nextTick, reactive, ref, unref } from 'vue';
import {
  channelValue,
  clickGetDeviceInfo,
  channels,
  init,
  login,
  clickLogout,
  mouseDownPTZControl,
  clickOpenSound,
  clickCloseSound,
  startRealPlay,
  clickStopRealPlay,
  hideWindow,
  changeWndNum,
  PTZZoomout,
  PTZZoomStop,
  PTZZoomIn,
  PTZFocusIn,
  PTZFoucusStop,
  PTZFoucusOut,
  PTZIrisIn,
  PTZIrisStop,
  PTZIrisOut,
  showWindow,
  dateFormat,
  mouseUpPTZControl,
  initChannelList,
  destroy,
  clickGetOSDTime,
  getWindowStatus,
  getCurWindowIndex,
  stopRealPlayByIndex,
  getAllWindowIndex,
} from '@/utils/webVideoCtrl';

import { addRealTimeMarkItem } from '@renderer/src/utils/ipc';
import { ElMessage } from 'element-plus';
import { userSystemStore } from '@/store';
import { useEventBus } from '@vueuse/core';

const systemStore = userSystemStore();
const loginEventBus = useEventBus('login');

const formRef = ref();

const data = reactive({
  ip: '192.168.2.64', //你的ip
  port: '80',
  userName: 'admin', //账号
  password: 'qwer7890', //密码
  videoLogin: false,
});

const markInfo = reactive({
  createTime: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
  type: '',
  channelNo: '',
  desc: '',
  rules: {
    type: { required: true, message: '请输入标注分类标签', tirgger: 'blur' },
  },
});

const dialogVisible = ref(false);

//窗口分割
const windowValue = ref('2*2');
const windowOptions = [
  {
    value: '1*1',
    label: '1*1',
  },
  {
    value: '2*2',
    label: '2*2',
  },
  {
    value: '3*3',
    label: '3*3',
  },
  {
    value: '4*4',
    label: '4*4',
  },
];

//云台控制-左边按钮
const leftCtrBtnList = reactive([
  {
    value: 5,
    name: '左上',
  },
  {
    value: 1,
    name: '上',
  },
  {
    value: 7,
    name: '右上',
  },
  {
    value: 3,
    name: '左',
  },
  {
    value: 9,
    name: '自动',
  },
  {
    value: 4,
    name: '右',
  },
  {
    value: 6,
    name: '右下',
  },
  {
    value: 2,
    name: '下',
  },
  {
    value: 8,
    name: '右下',
  },
]);

//云台控制-右边按钮
const rightCtrlBtnList = reactive([
  {
    value: 1,
    name: '变倍+',
  },
  {
    value: 2,
    name: '变倍-',
  },
  {
    value: 3,
    name: '聚焦+',
  },
  {
    value: 4,
    name: '聚焦-',
  },
  {
    value: 5,
    name: '光圈+',
  },
  {
    value: 6,
    name: '光圈-',
  },
]);

const loginoutClick = (data) => {
  const allIndexs = getAllWindowIndex();
  // 第一次索引0不会存在
  stopRealPlayByIndex(0);
  allIndexs.forEach((index) => {
    stopRealPlayByIndex(index);
  });
  clickLogout(data);
  systemStore.$patch({ videoData: {} });
  systemStore.$patch({ channels: [] });
  channleList.value = [];
  channelValue.value = '';
};

const rightCtrlDown = (value) => {
  switch (value) {
    case 1:
      PTZZoomIn();
      break;
    case 2:
      PTZZoomout();
      break;
    case 3:
      PTZFocusIn();
      break;
    case 4:
      PTZFoucusOut();
      break;
    case 5:
      PTZIrisIn();
      break;
    case 6:
      PTZIrisOut();
      break;
    default:
      break;
  }
};

const rightCtrlUp = (value) => {
  switch (value) {
    case 1:
    case 2:
      PTZZoomStop();
      break;
    case 3:
    case 4:
      PTZFoucusStop();
      break;
    case 5:
    case 6:
      PTZIrisStop();
      break;
    default:
      break;
  }
};

const channleList = ref([]);

const loginClick = (data) => {
  login(data)
    .then((result) => {
      data.videoLogin = true;
      initChannelList(data)
        .then((result) => {
          channleList.value = result;
        })
        .catch((error) => {
          console.log('获取通道失败error', error);
        });
    })
    .catch((error) => {
      if (error.errorCode === 403 || error.errorCode === 2001) {
        initChannelList(data)
          .then((result) => {
            channleList.value = result;
          })
          .catch((error) => {
            console.log('获取通道失败error', error);
          });
        console.log('您已登录，请勿重复登录！');
      } else {
        console.log('登录失败1', error);
        ElMessage.error('登录失败，请检查您的网络或账户信息！');
      }
    });

  if (data.videoLogin) {
    initChannelList(data)
      .then((result) => {
        channleList.value = result;
      })
      .catch((error) => {
        console.log('获取通道失败error', error);
      });
  }

  systemStore.$patch({ videoData: data });
  systemStore.$patch({ channels: channleList });
  ElMessage.success('登陆成功');
};

const submit = async (value) => {
  if (value) {
    let valid = true;
    try {
      await unref(formRef).validate();
    } catch (err) {
      console.log(err);
      valid = false;
      ElMessage.error('请输入标注分类标签');
    }
    if (!valid) return;

    try {
      await addRealTimeMarkItem([
        {
          id: '0',
          startTime: markInfo.createTime,
          endTime: '',
          label: markInfo.type,
          describe: markInfo.desc,
          channel: markInfo.channelNo,
          status: 0,
          createTime: markInfo.createTime,
          createUser: systemStore.getUserInfo().name,
        },
      ]);
      ElMessage.success('保存成功');
    } catch (err) {
      console.log(err);
    }
  }
  dialogVisible.value = false;
  showWindow();
};

onDeactivated(async () => {
  const allIndexs = getAllWindowIndex();
  // 第一次索引0不会存在
  stopRealPlayByIndex(0);
  allIndexs.forEach((index) => {
    stopRealPlayByIndex(index);
  });
  await destroy();
  await hideWindow();
});

onActivated(() => {
  nextTick(() => {
    initPlugin();
  });
});

//登录后监听事件
loginEventBus.on(() => {
  nextTick(() => {
    initPlugin();
  });
});

//录制与编辑,初始化及登录
const initPlugin = () => {
  if (!systemStore.$state.loginFlag) {
    return;
  }
  init();
  let videoData = systemStore.$state.videoData;
  if (!videoData.videoLogin) {
    login(data)
      .then((result) => {
        videoData = data;
        videoData.videoLogin = true;
        initChannelList(videoData)
          .then((result) => {
            channleList.value = result;
          })
          .catch((error) => {
            console.log('获取通道失败error', error);
          });
      })
      .catch((error) => {
        if (error.errorCode === 403 || error.errorCode === 2001) {
          console.log('您已登录，请勿重复登录！');
          initChannelList(videoData)
            .then((result) => {
              channleList.value = result;
            })
            .catch((error) => {
              console.log('获取通道失败error', error);
            });
        } else {
          console.log('登录失败2', error);
          ElMessage.error('登录失败，请检查您的网络或账户信息！');
        }
      });
    systemStore.$patch({ videoData: {} });
  }
};

const osdTime = ref('');

//标注
const mark = () => {
  markInfo.type = '';
  markInfo.desc = '';

  if (!systemStore.videoData.videoLogin) {
    ElMessage.error(' 请先登录设备');
    return;
  }

  // 1.获取当前窗口信息
  const wStatus = getWindowStatus(getCurWindowIndex());
  console.log('wStatus', wStatus);
  if (wStatus === null) {
    ElMessage.error('请选择正在预览窗口');
    return;
  }
  if (wStatus.length === 0) {
    ElMessage.error('请选择窗口');
    return;
  } else if (wStatus.iPlayStatus === 0) {
    ElMessage.error('请点击开始预览');
    return;
  }
  markInfo.channelNo = wStatus.iChannelID;
  channleList.value.forEach((item) => {
    if (item.value === markInfo.channelNo) {
      markInfo.channelNo = item.label;
    }
  });
  // 2.获取当前窗口OSD时间信息
  let osdTime = clickGetOSDTime();
  osdTime.then((time) => {
    osdTime = time;
    markInfo.createTime = osdTime;
  });
  hideWindow();
  dialogVisible.value = true;
};

const handleClose = async () => {
  dialogVisible.value = false;
  await showWindow();
};
</script>

<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .top {
    flex: 1;
    overflow-x: hidden;
    overflow-y: hidden;
    display: flex;
    border-radius: 5px;
    background: #fff;

    .plugin {
      width: 100%;
      height: 100%;
      margin: 8px;
    }
  }

  .divider {
    border: solid rgb(240, 242, 245) 2px;
    height: 100%;
  }

  .loginInfo {
    display: flex;
    flex-direction: column;
    margin-top: 5px;

    .form {
      flex: 1;
      display: flex;
      flex-direction: row;
      margin-left: 5px;
      justify-content: center;
      align-items: center;
      margin-top: 20px;

      .item {
        size: 100px;
        margin-left: 10px;
      }
    }

    .login {
      display: flex;
      flex-direction: row;
      margin-left: 10px;
      justify-content: center;
      align-items: center;
      margin-top: 10px;

      .item {
        margin-left: 10px;
        width: 86px;
      }

      .login-list {
        display: flex;
        flex-direction: row;
        margin-left: 10px;
        justify-content: center;
        align-items: center;

        .title {
          width: 150px;
          font-weight: 500;
          font-size: 16px;
          color: #020f1b;
          font-style: normal;
        }
      }
    }
  }

  .bottom {
    height: 300px;
    width: 100%;
    margin: 4px;
    border-radius: 8px;
    display: flex;
    margin-bottom: 20px;

    .left {
      flex: 1;
      display: flex;
      flex-direction: column;

      .title {
        height: 26px;
        font-weight: 500;
        font-size: 16px;
        color: #020f1b;
        font-style: normal;
        margin-top: 20px;
      }

      .btn-preview {
        height: 26px;
        display: flex;
      }

      .btn-preview:nth-child(2) {
        margin-left: 13px;
      }

      .btn-ctrl {
        flex: 1;
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        grid-template-rows: repeat(3, 1fr);

        .btn {
          width: 80px;
        }

        .btn:nth-child(1) {
          margin-left: 12px;
        }
      }
    }

    .right {
      flex: 1;
      display: flex;
      flex-direction: column;

      .title {
        height: 26px;
        font-weight: 500;
        font-size: 16px;
        color: #020f1b;
        font-style: normal;
        margin-top: 40px;
        display: flex;
        justify-content: center;
        align-items: center;

        .ritht-title {
          width: 150px;
        }

        .select {
          margin-left: 10px;
          width: 125px;
        }
      }

      .btn-ctrl {
        margin-top: 51px;
        flex: 1;
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(3, 1fr);

        .btn {
          width: 80px;
        }

        .btn:nth-child(1) {
          margin-left: 12px;
        }
      }
    }
  }
}

.dialogContent {
  background-color: rgb(240, 242, 245);
  display: flex;
  flex-direction: column;

  .title {
    display: flex;
    flex-direction: row;
    height: 58px;
    justify-content: flex-start;
    align-items: center;

    .item {
      font-weight: 500;
      font-size: 16px;
      color: #020f1b;
      font-style: normal;
      margin-left: 10px;
    }

    .item2 {
      font-weight: 500;
      font-size: 16px;
      color: #020f1b;
      font-style: normal;
      margin-left: 10px;
      padding: 0 3px;
    }
  }

  .form {
    .type {
      text-align: center;
    }

    .desc {
      min-height: 150px;
      max-height: 210px;
    }
  }
}
</style>
